﻿using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

namespace MGFramework {

    public enum SceneID {
        GAMEGATE,
        GAMESCENE,
        LOADING
    }

    public class LoadingScene : MonoBehaviour
    {
        private AsyncOperation async = null;
        private static int sceneID = 0;

        private Text progressText;
        private Scrollbar progressBar;

        void Awake()
        {
            //释放未被引用的Asset
            Resources.UnloadUnusedAssets();
            //强制对所有代进行垃圾回收
            GC.Collect();
            //挂起当前线程，直到处理终结器队列的线程清空该队列为止
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

        void Start()
        {
            //进度条
            progressBar = transform.Find("ProgressBar").GetComponent<Scrollbar>();
            //进度数值
            progressText = transform.Find("ProgressBar/ProgressText").GetComponent<Text>();

            //加载时不销毁这个物体
            DontDestroyOnLoad(transform.gameObject);

            //开始加载场景
            StartCoroutine("LoadScene");
        }

        //异步加载
        IEnumerator LoadScene()
        {
            int virtualProgress = 80;
            int realProgress = 0;

            async = SceneManager.LoadSceneAsync(sceneID);
            async.allowSceneActivation = false;

            //使用async.progress 打包后在安卓手机下运行会死循环
            while (async.progress < 0.8f)
            {
                realProgress = (int)async.progress * 100;
                SetLoadingPercentage(realProgress);
            }
            
            //虚拟的加载进程，每20毫秒加1
            while (virtualProgress < 100)
            {
                virtualProgress+=4;
                SetLoadingPercentage(virtualProgress);
                yield return new WaitForEndOfFrame();
                yield return new WaitForSeconds(0.01f);
            }
            //加载完成后，暂停0.1s进入游戏/菜单界面，并销毁加载界面
            yield return new WaitForSeconds(0.02f);
            async.allowSceneActivation = true;
            GameObject.Destroy(this.gameObject);
        }

        private void SetLoadingPercentage(int virtualProgress)
        {
            if (virtualProgress <= 100)
            {
                progressText.text = virtualProgress.ToString() + "%";
                progressBar.size = (float)virtualProgress / 100;
            }
        }

        /// <summary>
        /// 加载场景
        /// </summary>
        /// <param name="id">场景id</param>
        public static void LoadNextScene(SceneID id)
        {
            sceneID = (int)id;
            SceneManager.LoadScene((int)SceneID.LOADING);
        }
    }

}